package com.huluobo.mvidemo.news

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import javax.inject.Inject

/**
 *  Created by LC on 2025/1/13.
 */
@HiltViewModel
class NewsViewModel @Inject constructor(private val newsRepo: NewsRepo) : ViewModel() {
    //存放意图的管道
    val channel = Channel<NewsIntent> { Channel.UNLIMITED }

    //可变的状态,用于更新UI,就是LiveData,之前mvvm保存的是成功和失败的2个LiveData
    //MVI中保存的是状态,目前状态分为3种情况
    private var _state = MutableStateFlow<NewsState>(NewsState.onLoading)
    val state: StateFlow<NewsState>
        get() = _state

    init {
        viewModelScope.launch {
            channel.receiveAsFlow().collect {
                when (it) {
                    is NewsIntent.getNews -> {
                        val map = mutableMapOf<String, Int>()
                        map["page"] = 0
                        val json = Gson().toJson(map)
                        val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), json)
                        getNews(body)
                    }
                }
            }
        }
    }

    //请求新闻的方法
    fun getNews(body: RequestBody) {
        viewModelScope.launch {
            newsRepo.getNews(body)
                .flowOn(Dispatchers.IO)
                .catch {
                    Log.i("TagA", it.message.toString())
                }.collect {
                    if (it.statuesCode.toInt() == 200) {
                        _state.value = NewsState.onSuccess(it)
                    } else {
                        _state.value = NewsState.onError(it.msg)
                    }
                }
        }
    }
}